const app = getApp();
const utils = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    provinces: [],
    citys: [],
    districts: [],
    selProvince: '选填',
    selCity: '选填',
    selDistrict: '选填',
    selProvinceIndex: 0,
    selCityIndex: 0,
    selDistrictIndex: 0,
    said: 0,
    addressData: null,
    cityList: [],
    CountyList: [],
    imgsrc: "",
    cardInfo: {
      name: '',
      mobile: '',
      position: '',
      company: '',
      wxid: '',
      phone: '',
      email: '',
      adress: '',
    },
    staffid: 0,
    avater: "",
    avaterimg: "",
    showMode: 0//首页版本显示：0个人版，1商家板
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.imgsrc) {
      this.setData({
        imgsrc: options.imgsrc
      })
    }
    if (options.staffid) {
      this.getStaffInfo(options.staffid);
      this.data.staffid = options.staffid;
    }
  },

  //自动获取手机号
  getPhoneNumber(e) {
    var that = this;
    var cardInfo = that.data.cardInfo;
    utils.getMobile(e, function (data) {
      cardInfo.mobile = data;
      that.setData({ cardInfo: cardInfo })
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 获取输入框的值
   */
  bindchangeName: function (e) {
    let cardInfo = this.data.cardInfo;
    cardInfo.name = e.detail.value;
    this.setData({
      cardInfo: cardInfo
    })
  },
  bindchangeMobile: function (e) {
    let cardInfo = this.data.cardInfo;
    cardInfo.mobile = e.detail.value;
    this.setData({
      cardInfo: cardInfo
    })
  },
  bindchangePosition: function (e) {
    let cardInfo = this.data.cardInfo;
    cardInfo.position = e.detail.value;
    this.setData({
      cardInfo: cardInfo
    })
  },
  bindchangeCompany: function (e) {
    let cardInfo = this.data.cardInfo;
    cardInfo.company = e.detail.value;
    this.setData({
      cardInfo: cardInfo
    })
  },
  bindchangeWxid: function (e) {
    let cardInfo = this.data.cardInfo;
    cardInfo.wxid = e.detail.value;
    this.setData({
      cardInfo: cardInfo
    })
  },
  bindchangePhone: function (e) {
    let cardInfo = this.data.cardInfo;
    cardInfo.phone = e.detail.value;
    this.setData({
      cardInfo: cardInfo
    })
  },
  bindchangeEmail: function (e) {
    let cardInfo = this.data.cardInfo;
    cardInfo.email = e.detail.value;
    this.setData({
      cardInfo: cardInfo
    })
  },
  bindchangeAdress: function (e) {
    let cardInfo = this.data.cardInfo;
    cardInfo.adress = e.detail.value;
    this.setData({
      cardInfo: cardInfo
    })
  },

  /**
   * 上传头像
   */
  uploadDetailImage: function (e) {
    var that = this;
    if (!that.data.imgsrc) {
      that.creatStaffInfo(that.data.avater);
    } else {
      wx.showLoading({
        title: '提交中',
        mask: true,
      })
      var url = app.globalData.host + '/api/tool/upload?operation=savecardavater';
      wx.uploadFile({
        url: url,
        filePath: that.data.imgsrc,
        name: 'fileData',
        formData: null,
        success: (resp) => {
          wx.hideLoading();
          var avater = JSON.parse(resp.data).Data;
          that.creatStaffInfo(avater);
        }
      })
    }
  },

  /**
   * 编辑名片
   */
  creatStaffInfo: function (avater) {
    let that = this;
    let cardInfo = that.data.cardInfo;
    if (!cardInfo.name) {
      wx.showToast({
        title: '请输入姓名！'
      })
      return;
    }
    if (!cardInfo.mobile) {
      wx.showToast({
        title: '请输入手机号！'
      })
      return;
    }
    if (!cardInfo.position) {
      wx.showToast({
        title: '请输入职位！'
      })
      return;
    }
    if (!cardInfo.company) {
      wx.showToast({
        title: '请输入公司！'
      })
      return;
    }
    wx.showLoading({
      title: '提交中',
      mask: true,
    })
    let selProvince = that.data.selProvince,
      selCity = that.data.selCity,
      selDistrict = that.data.selDistrict;
    if (cardInfo.industrycode == 0) {
      if (selProvince == "选填") {
        selProvince = ''
      }
      if (selCity == "选填") {
        selCity = ''
      }
      if (selDistrict == "选填") {
        selDistrict = ''
      }
    }
    // 商家版
    if (cardInfo.industrycode == 1) {
      if (selProvince == "必填" || selCity == "必填" || selDistrict == "必填") {
        wx.showToast({
          title: '请选择地址'
        })
        return;
      }
      if (!cardInfo.adress) {
        wx.showToast({
          title: '请输入详细地址'
        })
        return;
      }
    }
    var param = {
      "Id": that.data.staffid,
      "StoreId": app.globalData.storeId,
      "Uid": app.globalData.userInfo.Uid,
      "Avater": avater,
      "Name": cardInfo.name,
      "Mobile": cardInfo.mobile,
      "ProvinceName": selProvince,
      "CityName": selCity,
      "AreaName": selDistrict,
      "Phone": cardInfo.phone,
      "Email": cardInfo.email,
      "Position": cardInfo.position,
      "Company": cardInfo.company,
      "Address": cardInfo.adress,
      "Wxid": cardInfo.wxid,
      "regionid": 1,
      "VID": cardInfo.vid,
      "ShowMode": that.data.showMode
    }
    wx.request({
      url: app.globalData.host + '/api/staff/AddOrUpdateStaff',
      data: param,
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          wx.reLaunch({
            url: '/pages/index/index?id=' + that.data.staffid,
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false,
          })
        }
      },
    })
  },

  /**
   * 获取个人名片信息
   */
  getStaffInfo: function (staffid) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    let that = this;
    let cardInfo = that.data.cardInfo;
    wx.request({
      url: app.globalData.host + '/api/staff/getinfo?id=' + staffid,
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          cardInfo.name = res.data.Data.Name;
          cardInfo.mobile = res.data.Data.Mobile;
          cardInfo.position = res.data.Data.Position;
          cardInfo.company = res.data.Data.Company;
          cardInfo.wxid = res.data.Data.Wxid;
          cardInfo.phone = res.data.Data.Phone;
          cardInfo.email = res.data.Data.Email;
          cardInfo.adress = res.data.Data.Address;
          cardInfo.vid = res.data.Data.VID;
          cardInfo.industrycode = res.data.Data.IndustryCode;
          var ProvinceName = res.data.Data.ProvinceName;
          var CityName = res.data.Data.CityName;
          var AreaName = res.data.Data.AreaName;
          if (cardInfo.industrycode == 0) {
            if (ProvinceName == null || ProvinceName == '') {
              ProvinceName = "选填"
            }
            if (CityName == null || CityName == '') {
              CityName = "选填"
            }
            if (AreaName == null || AreaName == '') {
              AreaName = "选填"
            }
          } else {
            if (ProvinceName == null || ProvinceName == '') {
              ProvinceName = "必填"
            }
            if (CityName == null || CityName == '') {
              CityName = "必填"
            }
            if (AreaName == null || AreaName == '') {
              AreaName = "必填"
            }
          }

          that.getProvince(ProvinceName);
          that.data.showMode = res.data.Data.ShowMode;
          that.data.avater = res.data.Data.Avater;
          that.setData({
            cardInfo: cardInfo,
            selProvince: ProvinceName,
            selCity: CityName,
            selDistrict: AreaName,
          })
        }
      },
    })

  },

  /**
   * 获取省接口
   */
  getProvince: function (selProvince) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Tool/ProvinceList',
      success: function (res) {
        var provincesArray = JSON.parse(res.data.Data)
        var pinkArray = [];
        for (var i = 0; i < provincesArray.length; i++) {
          pinkArray.push(provincesArray[i].name);
          if (provincesArray[i].name == selProvince && selProvince != "选填") {
            that.getCityList(i + 1);
          }
        }
        that.setData({
          provinces: pinkArray
        })
      }
    })
  },
  //省值选择变化
  bindPickerProvinceChange: function (event) {
    var selIterm = this.data.provinces[event.detail.value];
    var provinceId = parseInt(event.detail.value) + 1;
    let selCity = '选填';
    let selDistrict = '选填';
    if (this.data.cardInfo.industrycode == 1) {
      selCity = '必填';
      selDistrict = '必填';
    }
    this.setData({
      selProvince: selIterm,
      selProvinceIndex: provinceId,
      selCity: selCity,
      selDistrict: selDistrict
    })
    this.getCityList(provinceId) //初始化市数据
  },
  /**
   * 获取市接口
   */
  getCityList: function (provinceid) {
    var that = this;
    var selCity = that.data.selCity;
    wx.request({
      url: app.globalData.host + '/api/Tool/CityList?provinceId=' + provinceid,
      success: function (res) {
        var cityList = JSON.parse(res.data.Data)
        var pinkCitys = [];
        for (var i = 0; i < cityList.length; i++) {
          pinkCitys.push(cityList[i].name);
          if (cityList[i].name == selCity && selCity != "选填") {
            that.getCountyList(cityList[i].id);
          }
        }
        that.setData({
          citys: pinkCitys
        })
        that.data.cityList = cityList;
      }
    })
  },
  //市值选择
  bindPickerCityChange: function (event) {
    var cityList = this.data.cityList;
    var selIterm = this.data.citys[event.detail.value];
    let selDistrict = '选填';
    if (this.data.cardInfo.industrycode == 1) {
      selDistrict = '必填';
    }
    for (var i = 0; i < cityList.length; i++) {
      if (selIterm == cityList[i].name) {
        var citysId = cityList[i].id
      }
    }
    this.setData({
      selCity: selIterm,
      selCityIndex: citysId,
      selDistrict: selDistrict
    })
    this.getCountyList(citysId)
  },
  /**
   * 当点击获取县地区
   */
  getCountyList: function (citysid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Tool/CityList?provinceId=' + citysid,
      success: function (res) {
        var CountyList = JSON.parse(res.data.Data)
        var pinkCounty = [];
        for (var i = 0; i < CountyList.length; i++) {
          pinkCounty.push(CountyList[i].name);
        }
        that.setData({
          districts: pinkCounty
        })
        that.data.CountyList = CountyList;
      }
    })
  },

  bindPickerChange: function (event) {
    var CountyList = this.data.CountyList
    var selIterm = this.data.districts[event.detail.value]
    for (var i = 0; i < CountyList.length; i++) {
      if (selIterm == CountyList[i].name) {
        var DistrictId = CountyList[i].id
      }
    }
    this.setData({
      selDistrict: selIterm,
      selDistrictIndex: DistrictId
    })
  },

  //设置市数据
  setCityList: function (cityName, countyName) {
    var that = this;
    var cityList = that.data.cityList;
    for (let i = 0; i < cityList.length; i++) {
      if (cityList[i].name == cityName) {
        that.setData({
          selCity: cityName,
          selCityIndex: cityList[i].id
        })
        that.getCountyList(cityList[i].id);
        setTimeout(function () {
          that.setCountyList(cityName, countyName)
        }, 500)
        break;
      }
    }
  },

  //设置地区数据
  setCountyList: function (cityName, countyName) {
    var CountyList = this.data.CountyList;
    for (let i = 0; i < CountyList.length; i++) {
      if (CountyList[i].name == countyName) {
        this.setData({
          selDistrict: countyName,
          selDistrictIndex: CountyList[i].id
        })
      }
    }
  },

  //获取当前位置
  getMyLocation: function () {
    var that = this
    wx.getLocation({
      altitude: true,
      success: function (res) {
        var lat = res.latitude
        var lng = res.longitude      
        that.getRegionByGeo(lat, lng);
      },
    })
  },

  //获取地区信息
  getRegionByGeo: function (lat, lng) {
    wx.showLoading({title: '自动获取中',mask: true,})
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/tool/GetRegionByGeo?lat=' + lat + '&lng=' + lng,
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          let selProvince = res.data.Data.ProvinceName;
          let selCity = res.data.Data.CityName;
          let selDistrict = res.data.Data.Name;
          let cardInfo = that.data.cardInfo;
          if (selProvince == null || selCity == null || selDistrict == null || selDistrict == '未知区域') {
            utils.showToast('定位获取失败，可手动选择');          
            return;
          }                
          cardInfo.adress = res.data.Data.Address;
          that.setData({
            selProvince: selProvince,
            selCity: selCity,
            selDistrict: selDistrict,
            cardInfo: cardInfo,
          })
        }
      },
    })
  }
})